package com.rtx.wms.std.qm.service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.doudian.open.api.coupons_extendCertValidEndByOrder.param.Op;
import com.qimen.api.QimenClient;
import com.qimen.api.QimenRequest;
import com.qimen.api.request.EntryorderConfirmRequest;
import com.qimen.api.request.ReturnorderConfirmRequest;
import com.qimen.api.request.ReturnorderConfirmRequest.OrderLine;
import com.qimen.api.response.ReturnorderConfirmResponse;
import com.rtx.wms.std.asn.bean.ApiReceiptdetailfinish;
import com.rtx.wms.std.asn.bean.ApiReceiptfinish;
import com.rtx.wms.std.common.bean.WmsConstant;
import com.rtx.wms.std.log.bean.WmsLogBo;
import com.rtx.wms.std.log.service.impl.ReturnorderConfirmLog;
import com.taobao.api.ApiException;
import com.taobao.api.internal.util.XmlWriter;

import cn.hutool.core.date.DateUtil;

/**
 * ASN销售退货入库回传
 */
@Service
public class ReturnorderConfirmService extends QimenService{

	private Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
	ReturnorderConfirmLog returnorderConfirmLog;
	
	
	public void returnorderConfirm(String wmwhseid,ApiReceiptfinish apiReceiptfinish) {
		QimenClient client = getQimenClient();
		//利发测试
		if(Arrays.asList("C1689650364732,C1688969618777".split(",")).contains(apiReceiptfinish.getQmcustomerid())) {
			client = getTestQimenClient();
		}
		if(apiReceiptfinish.getQmcustomerid().startsWith("C")) {
			client = getTestQimenClient();
		}
		
		ReturnorderConfirmRequest req = new ReturnorderConfirmRequest();
		req.setCustomerId(apiReceiptfinish.getQmcustomerid());
	    req.setVersion("2.0");
		ReturnorderConfirmRequest.ReturnOrder order =  new ReturnorderConfirmRequest.ReturnOrder();
		order.setOutBizCode(UUID.randomUUID().toString());
		order.setReturnOrderId(apiReceiptfinish.getBatchid());
		//order.setOutBizCode(outBizCode);
		order.setOrderConfirmTime(DateUtil.format(apiReceiptfinish.getExpectedreceiptdate(),"yyyy-MM-dd HH:mm:ss"));
		order.setReturnReason(apiReceiptfinish.getRtxreturnreason());
		order.setLogisticsCode(apiReceiptfinish.getCarrierkey());
		order.setLogisticsName(apiReceiptfinish.getCarriername());
		order.setExpressCode(apiReceiptfinish.getCarrierreference());
		order.setReturnOrderCode(apiReceiptfinish.getExternreceiptkey());
		ReturnorderConfirmRequest.SenderInfo senderInfo = new ReturnorderConfirmRequest.SenderInfo();
		senderInfo.setName(apiReceiptfinish.getShipfromcontact());
		senderInfo.setZipCode(apiReceiptfinish.getShipfromzip());
		senderInfo.setMobile(apiReceiptfinish.getShipfromphone());
		senderInfo.setEmail(apiReceiptfinish.getShipfromemail());
		senderInfo.setProvince(apiReceiptfinish.getShipfromstate());
		senderInfo.setCity(apiReceiptfinish.getShipfromcity());
		senderInfo.setArea(apiReceiptfinish.getShipfromaddressline2());
		senderInfo.setTown(apiReceiptfinish.getShipfromaddressline3());
		senderInfo.setDetailAddress(apiReceiptfinish.getShipfromaddressline1());
		order.setSenderInfo(senderInfo);
		order.setRemark(apiReceiptfinish.getNotes());
		order.setOrderType(apiReceiptfinish.getRtxqmtype());
		order.setWarehouseCode(apiReceiptfinish.getRtxpofromhourse());
		List<OrderLine> lines = new ArrayList<ReturnorderConfirmRequest.OrderLine>();
		for (ApiReceiptdetailfinish apiReceiptdetailfinish : apiReceiptfinish.getDetails()) {
			OrderLine line = new OrderLine();
			line.setOrderLineNo(apiReceiptdetailfinish.getExternlineno());
			line.setItemCode(apiReceiptdetailfinish.getSku());
			Double qtyexpected =  Double.parseDouble(apiReceiptdetailfinish.getQtyexpected());
			Double actualQty =  Double.parseDouble(apiReceiptdetailfinish.getQtyreceived());
			line.setPlanQty(qtyexpected.longValue());
			line.setActualQty(actualQty.longValue()+"");
			lines.add(line);
		}
		req.setOrderLines(lines);
		req.setReturnOrder(order);
		WmsLogBo logBo = new WmsLogBo();
		try {
			
			handle2366(req,apiReceiptfinish);
			
	        logBo.setOriginalData(apiReceiptfinish);
	        logBo.setApiRequest(req);
			
			String uuid = UUID.randomUUID().toString();
			XmlWriter writer = new XmlWriter(true, "request", QimenRequest.class);
			String requestStr = writer.write(req);
			logger.info("uuid{}-externreceiptkey-{}-returnOrder回传数据:{}",uuid,apiReceiptfinish.getExternreceiptkey(),requestStr);
			ReturnorderConfirmResponse rsp = client.execute(req);
			logBo.setApiResponse(rsp);
			logger.info("uuid{}-externreceiptkey-{}-returnOrder回传数据:{}",uuid,apiReceiptfinish.getExternreceiptkey(),JSON.toJSONString(rsp));
			if(rsp.isSuccess()){
				apiReceiptfinish.setEdiflag(WmsConstant.SUCCESS_FLAG);
			}else{
				String msg = Optional.ofNullable(rsp.getMessage()).orElse("");
				if(msg.contains("订单已出库")) {
					apiReceiptfinish.setEdiflag(WmsConstant.SUCCESS_FLAG);
					apiReceiptfinish.setEdimsg(rsp.getMessage());
				}else {
					apiReceiptfinish.setEdiflag(WmsConstant.FAIL_FLAG);
					apiReceiptfinish.setEdimsg(rsp.getMessage());
				}
			}
		} catch (ApiException e) {
           logger.error("销售退货入库：{}回传奇门异常",apiReceiptfinish.getReceiptkey(),e);
           apiReceiptfinish.setEdiflag(WmsConstant.FAIL_FLAG);
           apiReceiptfinish.setEdimsg(e.getMessage());
           logBo.setMsg(e.getMessage());
       }
		
		try {
			returnorderConfirmLog.recordLog(wmwhseid, logBo);
		} catch (Exception e) {
			logger.error("记录日志异常",e);
		}
	}
	
	 /**
	    * 兆君回传逻辑
	* @param req
	* @param apiOrdersfinish
	*/
	void handle2366(ReturnorderConfirmRequest req,ApiReceiptfinish r){
	if("2366".equals(r.getStorerkey())) {
		req.getReturnOrder().setWarehouseCode(r.getRtxpofromhourse());
		req.getReturnOrder().setOwnerCode(r.getDefault01());
	}
}

}
